package ws.db.writetable;

import java.util.ArrayList;
import java.util.Iterator;

import ws.db.ColumnAttrPair;
import ws.db.execsql.ExecSQL;
import ws.db.sql.InsertSQLUseArray;
import ws.db.sql.SQLInterface;
import ws.log.Log;


/**
 * InsertObject has two methods.
 * 1 insert one object.
 * 2 insert serveral objects at one time.
 * */
public class InsertObject extends WriteObject {

	protected ArrayList objs;	//use for serval objs operate.
	 
	public InsertObject(String m_table,Object obj,
			 ArrayList<ColumnAttrPair> columnAttrPairs){
		super.table = m_table;
		super.obj = obj;
		super.columnAttrPairs = columnAttrPairs;
	}
	
	public InsertObject(String m_table,ArrayList objs,
			ArrayList<ColumnAttrPair> columnAttrPairs){
		super.table = m_table;
		this.objs = objs;
		super.columnAttrPairs = columnAttrPairs;
	}
	
	/**
	 * Save serval objs.
	 * 
	 * */
	public int[] operateServalRecords(){
		int result[];
		if(objs==null)return null;
		Iterator its = objs.iterator();
		ArrayList<SQLInterface> sqls = new ArrayList<SQLInterface>();
		String columns[] = new String[columnAttrPairs.size()];
		ColumnAttrPair.ChangArrayListToStringArray(columnAttrPairs, columns);
		//construct sqls .
		try{
			while(its.hasNext()){
				Object obj = its.next();
				String values[] = super.getValues(obj, columnAttrPairs);
				SQLInterface sql = constructSQL(table,where,columns,values);
				sqls.add(sql);
			}
		}
		catch(NullPointerException nullPointerEx){
			Log.writeDBMiddleLayerLog("从类对象得到值错误", nullPointerEx);
		}
		//call execute method.
		ExecSQL execsql = new ExecSQL();
		return execsql.execBatchCommand(sqls);
	}
	
	protected SQLInterface constructSQL(String m_table,String m_where,String[] columns,String[] values){
	 	return  new InsertSQLUseArray(table,columns,values);
	 	
	
	}
	
}
